package org.xxpay.apibase.util;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;

/**
* @Description: 支付工具类
* @author xxpay
*/
public class PayKit {

    private static final Logger logger = LoggerFactory.getLogger(PayKit.class);
    private static final String ENCODING_CHARSET_UTF8 = "UTF-8";


    /*
     * 功能描述:
     * 计算签名值：
     * 【常见典型类型】：  key=V& 形式拼接，最后拼接秘钥key的格式
     * @param map 参数Map
     * @param key 商户秘钥
     * @Return: java.lang.String
     * @Author: xxpay
     */
    public static String genSignNormal(Map<String,Object> map, String key){

        ArrayList<String> list = new ArrayList<>();
        for(Map.Entry<String,Object> entry:map.entrySet()){
            if(null != entry.getValue() && !"".equals(entry.getValue())){
                list.add(entry.getKey() + "=" + entry.getValue() + "&");
            }
        }
        int size = list.size();
        String [] arrayToSort = list.toArray(new String[size]);
        Arrays.sort(arrayToSort, String.CASE_INSENSITIVE_ORDER);
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < size; i ++) {
            sb.append(arrayToSort[i]);
        }
        String result = sb.toString();
        result += "key=" + key;
        result = md5(result, ENCODING_CHARSET_UTF8).toUpperCase();
        return result;
    }


    /**
     * <p><b>Description: </b>MD5
     * <p>2018年9月30日 上午11:33:19
     * @param value
     * @param charset
     * @return
     */
    public static String md5(String value, String charset) {

        MessageDigest md = null;
        try {
            if (StringUtils.isEmpty(charset)) charset = ENCODING_CHARSET_UTF8;
            byte[] data = value.getBytes(charset);
            md = MessageDigest.getInstance("MD5");
            byte[] digestData = md.digest(data);
            return toHex(digestData);
        } catch (NoSuchAlgorithmException e) {

            logger.error("e", e);
            return null;

        } catch (UnsupportedEncodingException e) {

            logger.error("e", e);
            return null;
        }
    }

    public static String toHex(byte input[]) {
        if (input == null)
            return null;
        StringBuffer output = new StringBuffer(input.length * 2);
        for (int i = 0; i < input.length; i++) {
            int current = input[i] & 0xff;
            if (current < 16)
                output.append("0");
            output.append(Integer.toString(current, 16));
        }

        return output.toString();
    }

}
